<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace think\template\taglib\api;

use think\Db;
use app\home\logic\FieldLogic;

/**
 * 积分商城商品分页列表标签
 */
class TagMemgift extends Base
{
    //初始化
    protected function _initialize()
    {
        parent::_initialize();
        $this->score = getUsersConfigData('score');

    }

    /**
     * 获取分页列表
     * @author wengxianhu by 2018-4-20
     */
    public function getScoreGoodList($param = array())
    {
        //排序字段
        $param['orderby'] = !empty($param['orderby']) ? trim($param['orderby']) : 'sort_order';
        //排序 升序/降序
        $param['orderway'] = !empty($param['orderway']) ? trim($param['orderway']) : 'desc';

        $page = !empty($param['page']) ? intval($param['page']) : 1;
        $pagesize = !empty($param['pagesize']) ? intval($param['pagesize']) : 15;

        $order = 'c.' . $param['orderby'] . ' ' . $param['orderway'];

        $where['c.is_del'] = 0;
        $where['c.status'] = 1;

        $paginate = array(
            'page' => $page,
        );
        $pages = Db::name('memgift')
            ->alias('c')
            ->field('c.*,a.litpic,a.title,a.users_price')
            ->join('archives a', 'a.aid = c.aid', 'LEFT')
            ->where($where)
            ->order($order)
            ->paginate($pagesize, false, $paginate);
        $result = $pages->toArray();

        foreach ($result['data'] as $key => $val) {
            $val['litpic'] = $this->get_default_pic($val['litpic']); // 默认封面图
            $result['data'][$key] = $val;
        }

        $users = session('users');
        $result['users_score'] = !empty($users['scores']) ? $users['scores'] : 0;

        $result['score_config'] = $this->score;

        empty($result['data']) && $result['data'] = false;

        return $result;
    }

    //积分商品详情
    public function getScoreGoodView($aid)
    {
        if (empty($aid)) {
            return false;
        }
        $detail = [];
        $field = 'c.*,a.aid,a.typeid,a.channel,a.title,a.subtitle,a.litpic,a.video_paths,a.video_times,a.author,a.click,a.arcrank,a.seo_title,a.seo_keywords,a.seo_description,a.users_price,a.market_price,a.users_free,a.old_price,a.stock_show,a.stock_count,a.prom_type,a.arc_level_id,a.downcount,a.add_time,a.attrlist_id,a.sales_show,a.sales_num,a.virtual_sales,a.goods_unit,b.typename';
        $detail = Db::name('memgift')
            ->alias('c')
            ->field($field)
            ->join('archives a', 'a.aid = c.aid', 'left')
            ->join('arctype b', 'a.typeid = b.id', 'left')
            ->where([
                'a.aid' => $aid,
                'c.status' => 1,
                'c.is_del' => 0,
            ])
            ->find();

        if (!empty($detail)) {
            $detail['sales_num'] = $detail['num'];
            // 销售量+虚拟销量
//            $detail['sales_num'] = intval($detail['sales_num']) + intval($detail['virtual_sales']);
            // 价格拆分
//            if (!empty($detail['users_price'])) {
//                $detail['users_price'] = unifyPriceHandle($detail['users_price']);
//                $detail['users_price_arr'] = explode('.', $detail['users_price']);
//            }
            // 视频处理
            $detail['video_paths'] = !empty($detail['video_paths']) ? request()->domain() . $detail['video_paths'] : '';
            if (!empty($detail['video_times'])) {
                if (intval($detail['video_times']) < 60) $detail['video_times'] = '00′' . $detail['video_times'] . '″';
            }
            // 商品运费处理
            if (!empty($detail['freight_fee_set']) && 2 === intval($detail['freight_fee_set']) && !empty($detail['freight_fee_tpl'])) {
                $where = [
                    'template_id' => intval($detail['freight_fee_tpl'])
                ];
                $freightTemplate = Db::name('shop_freight_template')->field('template_data, special_set, special_ids')->where($where)->find();
                $templateData = !empty($freightTemplate['template_data']) ? unserialize($freightTemplate['template_data']) : [];
                $detail['freight_fee'] = !empty($templateData[0]['freight_fee']) ? unifyPriceHandle($templateData[0]['freight_fee']) : 0;
            } else {
                $detail['freight_fee'] = '包邮';
            }

            // 模型标题处理
            $channeltype_row = \think\Cache::get('extra_global_channeltype');
            $channeltypeInfo = !empty($channeltype_row[$detail['channel']]) ? $channeltype_row[$detail['channel']] : [];
            $detail['channel_ntitle'] = !empty($channeltypeInfo['ntitle']) ? $channeltypeInfo['ntitle'] : '产品';
            $detail['seo_title'] = $this->set_arcseotitle($detail['title'], $detail['seo_title']); // seo标题
            $detail['litpic'] = $this->get_default_pic($detail['litpic']); // 默认封面图
            // $detail['forward'] = Db::name('users_forward')->where('aid',$aid)->count(); // 转发记录，废弃了，有需要就通过请求传参进行判断是否要查表返回数据，或者写成标签apiForward
            $detail['content'] = '';
            //只能是产品模型

            unset($detail['users_free']);
            unset($detail['downcount']);
            /*产品参数*/
            $productAttrModel = new \app\home\model\ProductAttr;
            $attr_list = $productAttrModel->getShopProductAttr($aid, 'a.attr_id,a.attr_name,b.attr_value,b.aid');
            $attr_list = !empty($attr_list[$aid]) ? $attr_list[$aid] : [];
            foreach ($attr_list as $key => $val) {
                $val['attr_value'] = htmlspecialchars_decode($val['attr_value']);
                unset($val['aid']);
                $attr_list[$key] = $val;
            }
            $detail['attr_list'] = !empty($attr_list) ? $attr_list : false;   //产品默认参数

            /*规格数据*/
            $detail['spec_attr'] = $this->getSpecAttr($aid);
            /* END */

            // 产品相册
            $productImgModel = new \app\home\model\ProductImg;
            $image_list = $productImgModel->getProImg($aid, 'aid,image_url,intro');
            $image_list = !empty($image_list[$aid]) ? $image_list[$aid] : [];
            foreach ($image_list as $key => $val) {
                $val['image_url'] = $this->get_default_pic($val['image_url']);
                isset($val['intro']) && $val['intro'] = htmlspecialchars_decode($val['intro']);
                $image_list[$key] = $val;
            }
            $detail['image_list'] = !empty($image_list) ? $image_list : false;

            /*可控制的主表字段列表*/
            $detail['ifcontrolRow'] = Db::name('channelfield')->field('id,name')->where([
                'channel_id' => $detail['channel'],
                'ifmain' => 1,
                'ifeditable' => 1,
                'ifcontrol' => 0,
                'status' => 1,
            ])->getAllWithIndex('name');

            // 设置默认原价
            $detail['old_price'] = $detail['users_price'];
            $detail['product_num'] = 1;
            $detail['spec_value_id'] = '';

//            $detail['cart_total_num'] = 0;
//            if (!empty($users['users_id'])) {
//                //购物车数量
//                $detail['cart_total_num'] = Db::name('shop_cart')->where(['users_id' => $users['users_id']])->sum('product_num');
//            }

            // 获取自定义字段的数据
            $customField = [];
            $addtableName = $channeltypeInfo['table'] . '_content';
            $detailRow = Db::name($addtableName)->field('id,aid,add_time,update_time', true)->where('aid', $aid)->find();
            if (!empty($detailRow)) {
                $fieldLogic = new \app\home\logic\FieldLogic();
                $detailExt = $fieldLogic->getChannelFieldList($detailRow, $detail['channel']); // 自定义字段的数据格式处理
                if (empty($channeltypeInfo['ifsystem'])) { // 自定义模型
                    // 如果存在自定义字段content，默认作为文档的正文内容。
                    // 如果不存在，将获取第一个html类型的内容，作为文档的正文内容。
                    if (!isset($detailExt['content'])) {
                        $contentField = Db::name('channelfield')->where([
                            'channel_id' => $detail['channel'],
                            'dtype' => 'htmltext',
                        ])->getField('name');
                        $detailExt['content'] = !empty($detailExt[$contentField]) ? $detailExt[$contentField] : '';
                    }
                }
                $detail['content'] = $detailExt['content'];
                unset($detailExt['content']);

                // 手机端详情内容
                if (isset($detailExt['content_ey_m'])) {
                    $detail['content'] = $detailExt['content_ey_m'];
                    unset($detailExt['content_ey_m']);
                }

                if (!empty($detailExt)) {
                    $field = 'name, title, dtype';
                    $customField = Db::name('channelfield')->field($field)->where([
                        'name' => ['IN', array_keys($detailExt)],
                        'channel_id' => $detail['channel'],
                        'ifeditable' => 1
                    ])->getAllWithIndex('name');
                    if (!empty($customField)) {
                        foreach ($customField as $key => $value) {
                            $customField[$key]['value'] = $detailExt[$key];
                        }
                    }
                }
                $customField = array_values($customField);
            }
            $detail['customField'] = !empty($customField) ? $customField : false;
            $detail['content'] = $this->html_httpimgurl($detail['content'], true); // 转换内容图片为http路径

            $detail['score_config'] = $this->score;
            $detail['my_limit'] = $detail['limit'];
            $detail['users_score'] = 0;
            $users = session('users');
            if (!empty($users)){
                $detail['users_score'] = Db::name('users')->where('users_id',$users['users_id'])->value('scores');

                $exchange_num = Db::name('shop_order_details')->where(['users_id'=>$users['users_id'],'product_id'=>$detail['aid']])->where('product_score','>',0)->sum('num');

                $detail['my_limit'] = $detail['limit'] - $exchange_num < 0 ? 0 : $detail['limit'] - $exchange_num;
            }

        }

        return $detail;
    }

    // 获取指定商品的规格数据
    public function getSpecAttr($aid = null, $order2 = '')
    {
        $ReturnData = $SpecData = $SpecValue = $SelectSpecData = [];
        if (empty($aid)) return $ReturnData;
//        if (empty($users['level_discount'])) $users['level_discount'] = 100;
//        // 会员折扣率
//        $SelectSpecData['users_discount'] = (intval($users['level_discount']) / 100);

        $SpecWhere = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        $order = 'spec_value_id asc, spec_id asc';
        $field = '*, false checked';
        $ProductSpecData = Db::name('product_spec_data')->field($field)->where($SpecWhere)->order($order)->select();
        if (!empty($ProductSpecData)) {
            $ProductSpecData = group_same_key($ProductSpecData, 'spec_mark_id');
            foreach ($ProductSpecData as $key => $value) {
                // $value[0]['checked'] = true;
                $SpecData[] = [
                    'spec_value_id' => $value[0]['spec_value_id'],
                    'spec_mark_id' => $value[0]['spec_mark_id'],
                    'spec_name' => $value[0]['spec_name'],
                    'spec_data_new' => $value,
                ];
            }

            unset($SpecWhere['spec_is_select']);
            $order2 = !empty($order2) ? $order2 : 'score_need asc,score_price asc';
            $ProductSpecValue = Db::name('product_spec_value')->where($SpecWhere)->order($order2)->select();

            if (!empty($ProductSpecValue)) {
                // 默认的规格值，取价格最低者
                $SelectSpecData['spec_value_id'] = explode('_', $ProductSpecValue[0]['spec_value_id']);

                // 若存在规格并且价格存在则覆盖原有价格
//                $SelectSpecData['users_price'] = sprintf("%.2f", strval($ProductSpecValue[0]['spec_price']) * strval($SelectSpecData['users_discount']));
                $SelectSpecData['score_need'] = $ProductSpecValue[0]['score_need'];

                // 产品原价
//                $SelectSpecData['old_price'] = $ProductSpecValue[0]['spec_price'];

                // 若存在规格并且库存存在则覆盖原有库存
                $SelectSpecData['stock_count'] = $ProductSpecValue[0]['score_stock'];

                // 价格及库存
                $SpecValue = $ProductSpecValue;
            }
            foreach ($SpecData as $key => $value) {
                foreach ($value['spec_data_new'] as $kk => $vv) {
                    // 追加默认规格class
                    if (in_array($vv['spec_value_id'], $SelectSpecData['spec_value_id'])) {
                        $SpecData[$key]['spec_data_new'][$kk]['checked'] = true;
                    }
                }
            }
        }

        $ReturnData = [
            'spec_data' => $SpecData,
            'spec_value' => $SpecValue,
            'select_spec_data' => $SelectSpecData
        ];

        return $ReturnData;
    }
}